﻿<%@ WebHandler Language="C#" Class="report" %>

using System;
using System.Web;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
using System.Data;

public class report : IHttpHandler {

    public string content; 
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/json";
        //string act = HttpContext.Current.Request.Params["act"];
        //string business_id = HttpContext.Current.Request.Params["business_id"];
        string opt = HttpContext.Current.Request.Params["opt"]; //操作下载download ，打印print
       
        string data_batch = HttpContext.Current.Request.Params["data_batch[]"]; //批号
        string ids = HttpContext.Current.Request.Params["ids[]"];             //商品ID+|+批号
        string data_optio = HttpContext.Current.Request.Params["data_optio"]; //文件类型

  
      

        if (opt == "download")
        {
            context.Response.Write("{\"code\": 1, \"url\": \"/search/report.ashx?opt=zip&ids[]=" + ids + "&data_batch=" + data_batch + "&data_optio=" + data_optio + "\"}");
        }
         if (opt == "print")
        {
            context.Response.Write("{\"code\":1,\"msg\":\"\u6253\u5370\u6587\u6863\u83b7\u53d6\u6210\u529f\",\"url\":[" + print(ids, data_optio) + "],\"info\":\"" + data_optio + "\"}");
        }
         if (opt == "zip")
         {
             download(DataBase(ids, data_optio));
         }
    }

    Common Init = new Common();
    MsSqlHelper mssql = new MsSqlHelper();
    DataTable dt;
    public string typename = "";
    
    
    public string DataBase(string ids,string data_optio)
    {
        string sql = "";
        string imageid = "";
        string[] sArray = ids.Split(',');

        foreach (string i in sArray)
        {

            string[] nArray = i.ToString().Split('|');
            string spid = nArray[0].ToString();
            string pihao = nArray[1].ToString();
            

            sql = "select distinct rtrim(a.imageid) as imageid from [ImageDoc] a(nolock),spkfk b(nolock) where b.spid=a.detailid and b.spid='" + spid + "'";
            switch (data_optio)
            {
                case "quanbu":
                    sql += " and a.type_id in('zc','pj','bz','sm','rf','pf','sf')";
                    break;
                case "bg":
                    sql += " and a.type_id='bg' and replace(rtrim(a.fzxx1),' ','')=replace(rtrim('" + pihao + "'),' ','')";
                    break;
                case "pj":
                    sql += " and a.type_id='pj'";
                    break;
                case "cj":
                    sql += " and a.type_id='cj'";
                    break;
                case "sm":
                    sql += " and a.type_id='sm'";
                    break;
                case "bz":
                    sql += " and a.type_id='bz'";
                    break;
                case "sf":
                    sql += " and a.type_id='sf'";
                    break;
                case "pf":
                    sql += " and a.type_id='pf'";
                    break;
                case "rf":
                    sql += " and a.type_id='rf'";
                    break;
                case "iquanbu":
                    sql += " and a.type_id in('fa','sh','ghssh','ghsfa','rk')";
                    break;
                case "fa":
                    sql += " and a.type_id='fa'";
                    break;
                case "sh":
                    sql += " and a.type_id='sh'";
                    break;
                case "ghssh":
                    sql += " and a.type_id='ghssh'";
                    break;
                case "ghsfa":
                    sql += " and a.type_id='ghsfa'";
                    break;
                case "rk":
                    sql += " and a.type_id='rk'";
                    break;
                default:
                    sql += " and 1=2";
                    break;
            }
            dt = mssql.ExecuteDt(sql);
            for (int n = 0; n < dt.Rows.Count; n++)
            {
                imageid += dt.Rows[n]["imageid"].ToString() + "#"+n+",";
            }
        }
        return imageid;
    }

    /// <summary>
    /// 预览JSON组装
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public string print(string ids,string data_optio)
    {
        string idsx=DataBase(ids, data_optio);
        string[] sArray = idsx.Split(',');
        string url = "";
        string sql = "";
        foreach (string i in sArray)
        {
           string[] iArray = i.ToString().Split('#');
           sql = "select rtrim(url) url from [ImageDoc](nolock) where  imageid ='" + iArray[0].ToString() + "'";
            DataTable dt = mssql.ExecuteDt(sql);
            for (int n = 0; n < dt.Rows.Count; n++)
            {
                //url += "\"" + dt.Rows[n]["url"].ToString() + "\",";
                url += "\"" + Init.imagefileurl(dt.Rows[n]["url"].ToString()) + "\",";
            }
        }
        if (url.IndexOf(",") > 0)
        {
            url = url.Remove(url.Length - 1, 1);
        }
        return url;
    }
    /// <summary>
    ///下载 组装
    /// </summary>
    /// <param name="ids"></param>
    public void download(string ids)
    {
        ZipFileByCode(ids);
    }


    /// <summary>
    /// 压缩打包文件
    /// </summary>
    /// <param name="ids">ids格式：url\新名字,url\新名字,...</param>
    public void ZipFileByCode(string ids)
    {
        string sql = "";
        try
        {
            content += "\r\n\r\n";
            content += "      " + Init.EntName + "\r\n";
            content += "====================================\r\n";
            //content += "单据编号：" + djbh + "\r\n";
            content += "====================================\r\n";
            content += "本出库单以下商品暂时没有商品信息：\r\n";
            content += "(格式：序号.类别_商品名称_批号)\r\n";
            content += "====================================\r\n";
            // = ""+Init.EntName+"\r\n\r\n\r\n质量管理部 联系方式：\r\n\r\n    联系电话：028-83420470\r\n\r\n    质量反馈QQ：2850897874\r\n\r\n    检验报告接收QQ：2850897881\r\n\r\n    检验报告查找QQ：2850519828\r\n\r\n图片资料打包\r\nCopyright © 2018 Sitaier QQ:613329777 All rights reserved\r\n\r\n\r\n" + ids;
            if (ids.Length != 0)
            {
                string[] sArray = ids.Split(',');

                MemoryStream ms = new MemoryStream();
                byte[] buffer = null;

                using (ZipFile file = ZipFile.Create(ms))
                {
                    file.BeginUpdate();
                    file.NameTransform = new MyNameTransfom();//通过这个名称格式化器，可以将里面的文件名进行一些处理。默认情况下，会自动根据文件的路径在zip中创建有关的文件夹。
                    
                    foreach (string i in sArray)
                    {
                        string[] iArray = i.ToString().Split('#');
                        DataTable dt = new DataTable();
                        sql = "select distinct rtrim(url) url,rtrim(imageid) plh,rtrim(c.spmch) as spmch,rtrim(b.extend) as extend,rtrim(type_id) type_id,rtrim(b.leibie) as leibie,rtrim(b.fzxx1) as pihao"                           
                           + " from [ImageDoc] b(nolock),spkfk c(nolock) where c.spid=b.detailid and b.imageid ='" + iArray[0].ToString() + "'";
                        dt = mssql.ExecuteDt(sql);

                        for (int n = 0; n < dt.Rows.Count; n++)
                        {
                            
                            var invalidFileNameChars = Path.GetInvalidFileNameChars();
                            string oldfilename = "H:\\" + dt.Rows[n]["url"].ToString().Replace("Upload", "TuPian");
                            string newfilename = dt.Rows[n]["spmch"].ToString() + "_" + dt.Rows[n]["leibie"].ToString() + "_" + dt.Rows[n]["pihao"].ToString() + "_" + iArray[1].ToString() + dt.Rows[n]["extend"].ToString();
                            foreach (char invalidFile in invalidFileNameChars)
                            {
                                newfilename = newfilename.Replace(invalidFile.ToString(), "");
                            }
                            if (File.Exists(oldfilename))
                            {                               
                                file.Add(oldfilename, newfilename);
                            }
                            if (File.Exists(Init.imagefilepath(dt.Rows[n]["url"].ToString())))
                            {
                                file.Add(Init.imagefilepath(dt.Rows[n]["url"].ToString()), newfilename);
                            }
                        }
                    }
                    content += "====================================\r\n";
                    content += "\r\n质量管理部 联系方式：\r\n    联系电话：028-83420470\r\n    质量反馈QQ：2850897874\r\n    检验报告接收QQ：2850897881\r\n    检验报告查找QQ：2850519828\r\n\r\n图片资料打包\r\nCopyright © 2018 Sitaier QQ:613329777 All rights reserved\r\n\r\n\r\n";
                    content += ids;
                    file.SetComment(content);
                    file.CommitUpdate();
                    buffer = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(buffer, 0, buffer.Length);
                }
                DateTime dts = DateTime.Now;
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=文档系统" + dts.ToLocalTime().ToString() + ".zip");
                HttpContext.Current.Response.BinaryWrite(buffer);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }
        catch (Exception ex)
        {
            Init.WriteLog(ex.ToString(),true);            
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
    {

        #region INameTransform 成员

        public string TransformDirectory(string name)
        {
            return null;
        }

        public string TransformFile(string name)
        {
            return Path.GetFileName(name);
        }

        #endregion
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}